<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    public function index()
    {
        if (auth()->check()) {
            return redirect(route('admin.index'));
        }
        return view('admin.login.login');
    }

    /**
     * @param Request $request
     * @return $this
     * @throws \Illuminate\Validation\ValidationException
     */
    public function submit(Request $request)
    {
        $post = $this->validate($request, [
            'username' => 'required',
            'password' => 'required'
        ]);
        $auth = auth()->attempt($post);
        if ($auth) {
//            $user = auth()->user();
//            $user->last_login_ip = $request->ip();
//            $user->last_login_time = time();
//            $user->login_times += 1;
//            $user->save();
            return redirect(route('admin.index'));
        }
        return redirect(route('admin.login'))->withErrors(['errors' => '登录失败']);
    }

    public function logout()
    {
        auth()->logout();
        return redirect(route('admin.login'))->with('success', '请重新登录');
    }
}
